package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.constant.Constant;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/*
    String cgiName= "appOrder/supplyJmtList";
*/

public class BookAlreadyListActivity extends BaseActivity implements LoadMoreListView.IXListViewListener{
    private LoadMoreListView mListView;
    Context mContext;
    private TextView tv_time_now,tv_money_now;//,tvToday,tvTime,tvDealTime;
    View tvMoreBest,tvMoreDetail,ivTime;
    DetailAdapter detailAdapter;

    ArrayList<BookAlready.SettledDetailBean.ContentBean> detailList = new ArrayList<>();

    String timeTitle,timeValue;
    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    private int requestSucceedCount = 0;
    private TagPager tagPager = new TagPager();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();

        mListView.setPullLoadEnable(true); // 设置可滑动
        mListView.setXListViewListener(this);// 设置滑动监听器
        mContext = this;
        timeTitle = getIntent().getStringExtra("timeTitle");
        timeValue = getIntent().getStringExtra("timeValue");
        tvBack.setVisibility(View.VISIBLE);
        ivBack.setVisibility(View.VISIBLE);
        toolbarTitle.setText("打款记录");//timeTitle+"已结算交易明细");

        View headView;
        headView = getLayoutInflater().inflate(R.layout.include_book_head_detail, null);

        tv_time_now = (TextView) headView.findViewById(R.id.tv_time_now);
        tv_money_now = (TextView) headView.findViewById(R.id.tv_money_now);
        tv_time_now.setText("打款日期:" + timeTitle);
        mListView.addHeaderView(headView);
        detailAdapter = new DetailAdapter(this,detailList,R.layout.item_book_detail_black);

        mListView.setAdapter(detailAdapter);
        baseback.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);
        initHeadView();
        requestOrderList(0);
    }

    void initView(){
        setContentView(R.layout.activity_list_minus);
        mListView = (LoadMoreListView)findViewById(R.id.listview);
        basetitle.setText("减免退");
        rightbtn.setText("帮助");
        rightbtn.setOnClickListener(this);
        vException = findViewById(R.id.v_exception);
        mainView = findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();
    }


    public void initException() {
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
    }


    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }


    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }
    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }


    private PtrMdFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void initHeadView() {
        ptrFrameLayout = (PtrMdFrameLayout) findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    boolean refreshFlag = false;
    public void refresh() {
        mListView.resetNoMore();
        refreshFlag = true;
        requestOrderList(0);
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
        requestOrderList( number + 1);
    }


    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            mListView.noMore();
        } else {
            mListView.stopLoadMore();
        }
    }


    OnRequestListener<BookAlready> onRequestListener = new OnRequestListener<BookAlready>() {
        @Override
        public BookAlready jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<BookAlready>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.order_no, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.order_no, arg + "", HttpRequest.FAIL_DATA_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0){
                showProgressView();
            }
        }

        @Override
        public void onResponse(ResponseEntity<BookAlready> response, Object tag) {
            showMainView();
            requestSucceedCount ++;
            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0) {
                detailList.clear();
            }
            BookAlready orderResponse = response.getResponseElement();
            BookAlready.SettledDetailBean content = orderResponse.getSettledDetail();
            tv_money_now.setText("合计:" + content.getTotalFee()+"元");
            tagPager.setLast(content.isLast());
            tagPager.setNumber(content.getNumber());
            tagPager.setSize(content.getSize());
            tagPager.setTotalElements(content.getTotalElements());
            detailList.addAll(content.getContent());
            detailAdapter.notifyDataSetChanged();
            if(content.getNumber()==0){
                if(refreshFlag) {
                    mListView.setSelection(0);
                    refreshFlag=false;
                }
            }
            updateViewStatus(requestTag);
            if(detailList.size()==0){
                showExceptionView(R.mipmap.order_no, "暂无订单", HttpRequest.FAIL_DATA_EMPTY);
            }

        }
    };


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
        }
    }

    private RequestTag requestTag = new RequestTag();
    String cgiName= "order/stats/supplySettleDetail";
    public void requestOrderList(int page) {

        RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
        Map<String, String> map = new HashMap<>();
        map.put("pageSize", "10");
        map.put("pageNumber", page + "");
        map.put("isDc",""+(getStoreInfo().isDc()?1:0));
        map.put("queryDate",timeValue);
/*        if(getStoreInfo()==null||getStoreInfo().getStore()==null){
            toast("数据错误，请刷新后重试");
            return;
        }   */       map.put("storeId", BaseApplication.getInstance().getStoreId());

        entity.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_order_supplier_order_incomeSettleDetail);
        entity.setParameters(map);
        requestTag.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_order_supplier_order_incomeSettleDetail;
        requestTag.action = page;
        request(entity, requestTag, onRequestListener);
    }


    class DetailAdapter extends CommonAdapter<BookAlready.SettledDetailBean.ContentBean> implements View.OnClickListener {
        public DetailAdapter(Context context, ArrayList<BookAlready.SettledDetailBean.ContentBean> runPacks, int a) {
            super(context, runPacks, a);
        }

        public void onClick(View v) {
            Object tag = v.getTag(R.id.item_key_position);
            if (tag != null && tag instanceof BookAlready.SettledDetailBean.ContentBean) {
                BookAlready.SettledDetailBean.ContentBean bean = (BookAlready.SettledDetailBean.ContentBean) tag;
                Intent detail = new Intent(mContext,H5OrderDetailActivity.class);
                detail.putExtra("orderId", bean.getOrder_id());
                detail.putExtra(Constant.KEY_WEB_URL, "http://m.epfresh.com/help/order_supply_new.html?orderId="+bean.getOrder_id());
                detail.putExtra(Constant.KEY_WEB_TITLE, "订单详情");
                startActivity(detail);


            }
        }

        @Override
        public int getCount() {
            if (mDatas == null) {
                return 0;
            }
            return mDatas.size();
        }

        @Override
        public void convert(final ViewHolder holder, final BookAlready.SettledDetailBean.ContentBean bean) {
            holder.getView(R.id.ll_item).setTag(R.id.item_key_position, bean);
            holder.setOnClickListener(R.id.ll_item, this);
            holder.setText(R.id.txt_order_time, bean.getCreate_order_time());
            holder.setText(R.id.txt_order_no, bean.getOrder_no());
            holder.setText(R.id.txt_money, bean.getTotalFee());
        }
    }

}
